package com.qdhh.enrollment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qdhh.enrollment.common.BusinessException;
import com.qdhh.enrollment.mapper.StudentMapper;
import com.qdhh.enrollment.model.Student;
import com.qdhh.enrollment.service.AdminUserManagementService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 管理员用户管理服务实现类
 */
@Service
public class AdminUserManagementServiceImpl extends ServiceImpl<StudentMapper, Student> implements AdminUserManagementService {

    @Override
    public Page<Student> listUsers(int page, int size, String keyword) {
        Page<Student> pageObj = new Page<>(page, size);
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getDeleted, 0);
        
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                    .like(Student::getNick, keyword)
                    .or()
                    .like(Student::getPhone, keyword)
                    .or()
                    .like(Student::getStudentNo, keyword)
            );
        }
        
        queryWrapper.orderByDesc(Student::getCreatedAt);
        return page(pageObj, queryWrapper);
    }

    @Override
    public Student getUserById(String id) {
        Student student = getById(id);
        if (student == null || (student.getDeleted() != null && student.getDeleted() == 1)) {
            throw new BusinessException("用户不存在");
        }
        return student;
    }

    @Override
    public void updateUserStatus(String id, Integer status) {
        Student student = getUserById(id);
        student.setStatus(status);
        student.setUpdatedAt(LocalDateTime.now());
        updateById(student);
    }

    @Override
    public void deleteUser(String id) {
        Student student = getUserById(id);
        student.setDeleted(1);
        student.setUpdatedAt(LocalDateTime.now());
        updateById(student);
    }
}

